import { fabric } from 'fabric'
import { mapState, mapMutations, mapGetters } from 'vuex'
/**
  * fabric的自定义属性:
  * myPrice 价格
  * params 价格map [{id:price}]
  * myTmp 模板
  * myPricePre 价格前缀'¥'
  * myPriceSuf: 价格后缀'元'
  * myFix: myPricePre || myPriceSuf
  * canvasId.toJSON(['myPrice', 'myTmp', 'params'])
  */
export const FabricMixin = {
  data () {
    return {
      canvasId: null,
      acTarget: null,
      fontColor: '#000000',
      fontSize: 30,
      // fontFamily: '',
      markPrice: ''
    }
  },
  computed: {
    ...mapState(['XFabricJson']),
    ...mapGetters(['GCanvasSize'])
  },
  methods: {
    ...mapMutations(['setFabricJson']),
    /**
     * 初始化fabric
     * @param {*} canvasId canvasId
     */
    initData (canvasId) {
      // this.fontFamily = this.defaultFont()
      this.canvasId = canvasId
      this.canvasId.setZoom(this.GCanvasSize.scaleLoad)
      this.canvasId.on('mouse:down', options => {
        this.onMouseDown(options)
      })
    },
    /**
     * 监听画布mouse:down事件
     * @param {*} options
     */
    onMouseDown (options) {
      this.acTarget = options.target
      // const pos = options.absolutePointer
      // 删除
      document.onkeydown = e => {
        if (e.keyCode === 46) { // 8back  46delete
          this.fDelTarget()
        }
      }
      // 处理元素
      this.canvasId.forEachObject(item => {
        // 清空空元素
        if (item.type === 'i-text' && !item.text) {
          this.canvasId.remove(item)
        }
      })
    },
    // defaultFont () {
    //   return document.documentElement.currentStyle ? document.documentElement.currentStyle : window.getComputedStyle(document.documentElement).fontFamily
    // },
    /**
     * 删除target
     */
    fDelTarget () {
      const acObj = this.canvasId.getActiveObject()
      if (!acObj || acObj.myTmp) return
      this.canvasId.remove(acObj)
      this.acTarget = null
    },
    fDrawText (text) {
      if (this.canvasId.size() >= 20) return this.$message.warning('一个水印最多支持二十个元素标签')
      const _this = this
      const acObj = this.canvasId.getActiveObject()
      if (!acObj) {
        const textStr = new fabric.IText(text, {
          borderColor: '#000000',
          editingBorderColor: '#000000',
          transparentCorners: false,
          cornerColor: '#ffffff',
          borderDashArray: [3, 3],
          padding: 8,
          cornerSize: 5,
          fill: _this.fontColor,
          fontSize: _this.fontSize
          // fontFamily: _this.fontFamily
        })
        this.canvasId.add(textStr).setActiveObject(textStr)
        textStr.enterEditing()
        this.acTarget = textStr
        this.fPosition(5)
      } else {
        if (acObj.myPrice) return
        acObj.set({
          text,
          dirty: true
        })
        this.canvasId.renderAll()
      }
    },
    fDrawPrice (price) {
      const priceStr = price ? price + '' : '999'
      const centerObj = this.canvasId.getCenter()
      const centerObjL = centerObj.left * this.GCanvasSize.scaleL
      const centerObjT = centerObj.top * this.GCanvasSize.scaleL
      const fixTargetAdd = new fabric.Text('¥', {
        borderColor: '#000000',
        editingBorderColor: '#000000',
        transparentCorners: false,
        cornerColor: '#3889d6',
        borderDashArray: [3, 3],
        padding: 0,
        cornerSize: 5,
        fill: '#000000',
        fontSize: 36
      })
      const textPrice = new fabric.Text(priceStr, {
        borderColor: '#000000',
        editingBorderColor: '#000000',
        transparentCorners: false,
        cornerColor: '#3889d6',
        borderDashArray: [3, 3],
        padding: 0,
        cornerSize: 5,
        fill: '#000000',
        fontSize: 56,
        myPrice: true
      })
      this.canvasId.add(textPrice)

      textPrice.set({
        left: centerObjL - textPrice.width * 0.5,
        top: centerObjT - textPrice.height * 0.5
      })
      this.canvasId.add(fixTargetAdd)
      fixTargetAdd.set({
        left: textPrice.left - fixTargetAdd.width - 5,
        top: textPrice.top + 15
      })
      fixTargetAdd.setCoords()
      textPrice.setCoords()
    },
    // 更新价格变量
    fUpdatePrice (price) {
      if (!this.canvasId) return
      let hasPrice = false
      this.canvasId.forEachObject(item => {
        if (item.myPrice) {
          hasPrice = true
          this.canvasId.setActiveObject(item)
          this.acTarget = item
          item.set({
            text: price + '',
            dirty: true
          })
          this.canvasId.renderAll()
        }
      })
      if (!hasPrice) this.fDrawPrice(price)
    },
    /**
     * 设置font-family
     * @param {*} font font-family
     */
    // fFontChange (font) {
    //   this.fontFamily = font
    //   // const myfont = new FontFaceObserver(font)
    //   const obj = this.canvasId.getActiveObject()
    //   if (!obj) return
    //   obj.set({
    //     fontFamily: font,
    //     dirty: true
    //   })
    //   this.canvasId.renderAll()
    // },
    /**
     * 设置FontSize
     * @param {Number} size 字体大小
     */
    fFontSize (size) {
      this.fontSize = size
      const obj = this.canvasId.getActiveObject()
      if (!obj) return
      if (obj.type === 'text' || obj.type === 'i-text') {
        obj.set('fontSize', size)
        obj.set('dirty', true)
        this.canvasId.renderAll()
      }
    },
    /**
     * 设置字体颜色
     * @param {String} color 字体颜色
     */
    fFontColor (color) {
      this.fontColor = color
      const obj = this.canvasId.getActiveObject()
      if (!obj) return
      if (obj.type === 'text' || obj.type === 'i-text') {
        obj.set('fill', color)
        obj.set('dirty', true)
        this.canvasId.renderAll()
      }
    },
    fPosition (index) {
      const acObj = this.canvasId.getActiveObject()
      if (!acObj) return
      const centerObj = this.canvasId.getCenter()
      const centerObjL = centerObj.left * this.GCanvasSize.scaleL
      const centerObjT = centerObj.top * this.GCanvasSize.scaleL
      const acObjW = acObj.width
      const acObjH = acObj.height
      let left = 0; let top = 0
      switch (index) {
        case 1: case 4: case 7: left = 0; break
        case 2: case 5: case 8: left = centerObjL - acObjW * 0.5; break
        case 3: case 6: case 9: left = centerObjL * 2 - acObjW; break
        default: left = 0
      }
      switch (index) {
        case 1: case 2: case 3: top = 0; break
        case 4: case 5: case 6: top = centerObjT - acObjH * 0.5; break
        case 7: case 8: case 9: top = centerObjT * 2 - acObjH; break
        default: top = 0
      }
      acObj.set({
        top,
        left,
        dirty: true
      })
      acObj.setCoords()
      this.canvasId.renderAll()
    },
    /**
     * 清空画板
     */
    fClearCanvas () {
      this.canvasId.clear()
    },
    /**
    * 反序列化 - 模板列表
    * @param {*} jsonStr
    */
    fLoadTmp (jsonStr, price) {
      return new Promise((resolve) => {
        this.fClearCanvas()
        this.canvasId.loadFromJSON(jsonStr, () => {
          this.canvasId.setZoom(this.GCanvasSize.scaleLoad)
          this.canvasId.forEachObject(item => {
            if (item.myTmp) {
              item.set('selectable', false)
            }
            if (item.myPrice) {
              item.set({
                text: price + '',
                dirty: true
              })
              this.canvasId.renderAll()
            }
          })
          resolve(this.canvasId)
        })
      })
    },
    /**
     * 反序列化 - 商品列表
     * @param {*} jsonStr
     */
    fLoadJson (jsonStr) {
      return new Promise((resolve) => {
        this.fClearCanvas()
        this.canvasId.loadFromJSON(jsonStr, () => {
          this.canvasId.setZoom(this.GCanvasSize.scaleLoad)
          this.canvasId.forEachObject(item => {
            if (item.myTmp) item.set('selectable', false)
          })
          resolve(this.canvasId)
        })
      })
    },
    handleJsonStr () {
      const jsonStr = JSON.stringify(this.canvasId.toJSON(['myPrice', 'myTmp', 'params']))
      this.setFabricJson(jsonStr)
      return jsonStr
    },
    dataURLtoBlob (dataurl) {
      var arr = dataurl.split(',')
      var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1])
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },
    fCanvasImg () {
      const url = this.canvasId.toDataURL()
      const blob = this.dataURLtoBlob(url)
      return blob
    },
    fSave () {
      this.canvasId.width = this.GCanvasSize.W
      this.canvasId.height = this.GCanvasSize.H
      // this.canvasId.setZoom(this.GCanvasSize.scaleL)
      this.canvasId.setZoom(this.GCanvasSize.scaleL)
      const url = this.canvasId.toDataURL()
      const blob = this.dataURLtoBlob(url)
      // a标签下载
      const elink = document.createElement('a')
      elink.download = '截图.png'
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      document.body.removeChild(elink)
    }
  }
}
